/**
 * 安装应用
 */
import { DependencyContainer, useTransaction, toSuccess, Router, ROOT } from '@sker/core'
import { useUpload } from '@sker/runtime';
import { dirname, join } from 'path';
import StreamZip from 'node-stream-zip'
import { ensureDirSync, moveSync } from 'fs-extra';
import { rimraf } from 'rimraf'
export default async (container: DependencyContainer) => {
    const router = new Router(container)
    const { scope, addon } = router;
    const root = container.resolve(ROOT)

    const item = await useTransaction(async (m) => {
        const fileName = await useUpload(info => {
            return `${scope}/${addon}/${info.filename}`
        });
        await new Promise<void>((resolve, reject) => {
            setTimeout(() => resolve(), 1000)
        })
        const filePath = join(root, 'attachments', fileName)
        const outFilePath = join(root, 'attachments', fileName.replace('.zip', ''))
        try {
            await rimraf(outFilePath)
        } catch (e) { }
        ensureDirSync(outFilePath)
        const pkgPath = await new Promise<string>((resolve, reject) => {
            const zip = new StreamZip({ file: filePath })
            let pkgPath: string | null = null;
            zip.on('error', (err) => {
                reject(err)
            })
            zip.on('ready', () => {
                zip.extract(null, outFilePath, (err, res) => {
                    resolve(pkgPath)
                    zip.close()
                })
            })
            zip.on('extract', (entry, output) => {
                const name = entry.name;
                if (name.includes('package.json')) {
                    pkgPath = output;
                }
            })
        })
        const pkg = require(pkgPath)
        try {
            const addonPath = join(root, 'addons', pkg.name)
            await rimraf(addonPath)
            moveSync(dirname(pkgPath), addonPath)
            await rimraf(outFilePath)
        } catch (e) {
        }
        return pkg
    })
    return toSuccess(item)
}
